package common.html;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TreeMap;

public class TableTag extends DefaultTag
{
    final static String NAME = "table";
    TreeMap<Integer, String> column = new TreeMap<Integer, String>();
    Rows rows = new Rows(column);

    public TableTag()
    {
        super(NAME);
    }

    TableTag tHeader(Integer index, String header)
    {
        column.put(index, header);
        return this;
    }

    TableTag tHeader(String... headers)
    {
        column.clear();
        int i = 0;
        for (String header : headers)
        {
            column.put(i++, header);
        }
        return this;
    }

    TableTag addBody(String... values)
    {
        rows.addRow(values);
        return this;
    }

    class Rows
    {
        List<List<String>> rows = new ArrayList<List<String>>();
        TreeMap<Integer, String> columnMap;

        Rows(TreeMap<Integer, String> columns)
        {
            this.columnMap = columns;
        }

        public void addRow(String... values)
        {
            if (column.size() != values.length && column.size() > values.length)
            {
                throw new RuntimeException("column more than input parameters.");
            }

            ArrayList<String> row = new ArrayList<String>();
            Collections.addAll(row, values);
            rows.add(row);
        }

        public void addAllRow(List<List<String>> rows)
        {
            this.rows = rows;
        }

        public void clean()
        {
            rows.clear();
        }

        public List<String> removeRow(int rowLine)
        {
            if (rowLine < rows.size())
            {
                return null;
            }

            return rows.remove(rowLine);
        }

        public List<String> rmFristLine()
        {
            return removeRow(0);
        }

        public List<String> rmLastLine()
        {
            return removeRow(rows.size());
        }
    }

}
